package com.example.myxm.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myxm.App;
import com.example.myxm.R;
import com.example.myxm.adapter.IncomeAdapter;
import com.example.myxm.adapter.PayDetailAdapter;
import com.example.myxm.auth.LoginManager;
import com.example.myxm.databinding.ActivityPayDetailBinding;
import com.example.myxm.module.ExpenseBean;
import com.example.myxm.module.IncomeBean;
import com.example.myxm.module.ResultBean;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class PayDetailActivity extends BaseActivity<ActivityPayDetailBinding> {
    private PayDetailAdapter adapter;

    @NonNull
    @Override
    protected ActivityPayDetailBinding getViewBinding(@NonNull LayoutInflater inflater) {
        return ActivityPayDetailBinding.inflate(inflater);
    }


    @Override
    protected void initData() {
        ResultBean<List<ExpenseBean>> payByUserBean = App.getDbHelperStatic().getExpensesByUserBean(LoginManager.getCurrentUserId(this));

        getBinding().toolbar.setNavigationIcon(R.drawable.ic_back);
        getBinding().toolbar.setTitle("支出详情");
        getBinding().toolbar.setNavigationOnClickListener(v -> finish());

        if (payByUserBean.getCode() ==200){
            List<ExpenseBean> payList =payByUserBean.getData();
            adapter = new PayDetailAdapter(this, payList);
            getBinding().listView.setAdapter(adapter);

            getBinding().tvTotalAmount.setText("¥："
                    + payByUserBean.getData().stream()
                    .mapToDouble(ExpenseBean::getAmount)
                    .sum() + " 元");
        }

        if (adapter!=null){
            adapter.setItemClick(new PayDetailAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(ExpenseBean incomeBean) {
                    if (incomeBean != null) {
                        showNewIncomeDialog(incomeBean, adapter);
                    } else {
                        Toast.makeText(PayDetailActivity.this, "无法获取收入信息", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }


    /**
     * 弹出“新增/编辑收入”对话框：
     *
     * @param incomeBean  如果不为 null，表示“编辑”；否则“新增”
     * @param adapter     如果“不为 null”，则在“编辑”后需 notifyDataSetChanged()
     */
    private void showNewIncomeDialog(ExpenseBean incomeBean, PayDetailAdapter adapter) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.in_come_dialog, null);


        EditText etMoney   = dialogView.findViewById(R.id.et_money_newin);
        TextView etTime    = dialogView.findViewById(R.id.et_time_newin);
        Spinner spType     = dialogView.findViewById(R.id.sp_type_newin);
        EditText etPayer   = dialogView.findViewById(R.id.et_payer_newin);
        EditText etRemark  = dialogView.findViewById(R.id.et_remark_newin);
        TextView btSave      = dialogView.findViewById(R.id.bt_save_newin);
        TextView btCancel    = dialogView.findViewById(R.id.bt_cancel_newin);
        TextView btDelete    = dialogView.findViewById(R.id.bt_delete_newin);
        TextView tvPay = dialogView.findViewById(R.id.tv_payer_newin);
        tvPay.setText("收款方");
        btDelete.setVisibility(View.VISIBLE);

        if (incomeBean != null) {
            etMoney.setText(String.valueOf(incomeBean.getAmount()));
            etTime.setText(incomeBean.getDate());
            int typePosition = findSpinnerPosition(spType, incomeBean.getType());
            if (typePosition >= 0) {
                spType.setSelection(typePosition);
            }
            etPayer.setText(incomeBean.getPayee());
            etRemark.setText(incomeBean.getNote());
        }


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();

        etTime.setOnClickListener(v -> {
            Calendar now = Calendar.getInstance();
            DatePickerDialog datePicker = new DatePickerDialog(this,
                    (view, year, month, dayOfMonth) -> {
                        int selYear = year;
                        int selMonth = month;
                        int selDay = dayOfMonth;

                        TimePickerDialog timePicker = new TimePickerDialog(this,
                                (timeView, hourOfDay, minute) -> {
                                    String result = String.format(
                                            Locale.getDefault(),
                                            "%04d-%02d-%02d %02d:%02d",
                                            selYear,
                                            selMonth + 1,
                                            selDay,
                                            hourOfDay,
                                            minute
                                    );
                                    etTime.setText(result);
                                },
                                now.get(Calendar.HOUR_OF_DAY),
                                now.get(Calendar.MINUTE),
                                true // 是否 24 小时制
                        );
                        timePicker.show();

                    },
                    now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH)
            );
            datePicker.show();
        });
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (getResources()
                    .getDisplayMetrics().widthPixels * 0.8f);
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.CENTER;
            window.setAttributes(params);
        }


        btCancel.setOnClickListener(v -> dialog.dismiss());


        btSave.setOnClickListener(v -> {
            String moneyStr = etMoney.getText().toString().trim();
            String timeStr  = etTime.getText().toString().trim();
            String typeStr  = spType.getSelectedItem() != null
                    ? spType.getSelectedItem().toString()
                    : "";
            String payerStr = etPayer.getText().toString().trim();
            String remarkStr= etRemark.getText().toString().trim();

            if (moneyStr.isEmpty() || timeStr.isEmpty()) {
                Toast.makeText(this,
                        "金额和日期不能为空",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            double moneyVal;
            try {
                moneyVal = Double.parseDouble(moneyStr);
            } catch (NumberFormatException ex) {
                Toast.makeText(this,
                        "请输入合法的数字金额",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (incomeBean == null) {
                ResultBean<IncomeBean> incomesByUserBean  = App.getDbHelperStatic().addIncomeBean(
                        LoginManager.getCurrentUserId(PayDetailActivity.this),
                        moneyVal,
                        timeStr,
                        typeStr,
                        payerStr,
                        remarkStr);
                if (incomesByUserBean.getCode() == 200) {
                    Toast.makeText(this,
                            "新增收入已保存",
                            Toast.LENGTH_SHORT).show();
                    refreshDataFromDb();
                } else {
                    Toast.makeText(this,
                            "新增失败，请稍后重试",
                            Toast.LENGTH_SHORT).show();
                }
            } else {

                incomeBean.setAmount(moneyVal);
                incomeBean.setDate(timeStr);
                incomeBean.setType(typeStr);
                incomeBean.setPayee(payerStr);
                incomeBean.setNote(remarkStr);

                ResultBean<Boolean> updated = App.getDbHelperStatic().updateIncomeBean(
                        incomeBean.getId(),
                        Double.parseDouble(moneyStr),
                        typeStr,
                        payerStr,
                        remarkStr);
                if (updated.getCode() == 200) {
                    Toast.makeText(this,
                            "修改已保存",
                            Toast.LENGTH_SHORT).show();

                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    Toast.makeText(this,
                            "修改失败，请稍后重试",
                            Toast.LENGTH_SHORT).show();
                }
            }


            dialog.dismiss();
        });

        btDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (incomeBean!=null){
                    ResultBean<Integer> integerResultBean = App.getDbHelperStatic().deleteExpensesByUserBean(incomeBean.getUserId(), incomeBean);
                    if (integerResultBean.getCode() == 200){
                        refreshDataFromDb();
                        dialog.dismiss();
                        Toast.makeText(PayDetailActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    /**
     * 根据给定的字符串 value，找到 Spinner 的 position。
     * 这里假设 Spinner 是用 ArrayAdapter<String> 或者相同字符串项初始化的。
     * 如果你的 Spinner 用的是自定义对象，那么需要自己改写比较逻辑。
     */
    private int findSpinnerPosition(Spinner spinner, String value) {
        for (int i = 0; i < spinner.getCount(); i++) {
            Object item = spinner.getItemAtPosition(i);
            if (item != null && item.toString().equals(value)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 如果想在新增/编辑后“立即刷新列表”，可以写一个单独方法：
     * （示例思路：重新从数据库获取一次最新数据，然后给新的 adapter 或者原 adapter 重新设置 list）
     */
    private void refreshDataFromDb() {
        ResultBean<List<ExpenseBean>> result = App.getDbHelperStatic()
                .getExpensesByUserBean(LoginManager.getCurrentUserId(this));
        if (result.getCode() == 200) {
            List<ExpenseBean> newList = result.getData();
            PayDetailAdapter adapter = new PayDetailAdapter(this, newList);
            getBinding().listView.setAdapter(adapter);

            // 重新设置 item 点击，方便再次编辑
            getBinding().listView.setOnItemClickListener(
                    (parent, view, position, id) -> {
                        ExpenseBean clicked = newList.get(position);
                        showNewIncomeDialog(clicked, adapter);
                    });
        } else {
            Toast.makeText(this,
                    "数据刷新失败：" + result.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }
}